from typing import Dict, Optional, List
import hashlib
import json
from datetime import datetime, timedelta
import secrets

class Permission:
    """权限类"""
    SELECT = "SELECT"
    INSERT = "INSERT"
    UPDATE = "UPDATE"
    DELETE = "DELETE"
    CREATE = "CREATE"
    DROP = "DROP"
    ADMIN = "ADMIN"

class User:
    """用户类"""
    def __init__(self, username: str, password_hash: str, permissions: List[str]):
        self.username = username
        self.password_hash = password_hash
        self.permissions = permissions
        self.created_at = datetime.now()
        self.last_login = None
        self.is_active = True

    def has_permission(self, permission: str) -> bool:
        """检查用户是否有指定权限"""
        return permission in self.permissions or Permission.ADMIN in self.permissions

class Session:
    """会话类"""
    def __init__(self, user: User, session_id: str):
        self.user = user
        self.session_id = session_id
        self.created_at = datetime.now()
        self.last_activity = datetime.now()
        self.is_active = True

    def is_expired(self, timeout_minutes: int = 30) -> bool:
        """检查会话是否过期"""
        return datetime.now() - self.last_activity > timedelta(minutes=timeout_minutes)

    def update_activity(self):
        """更新最后活动时间"""
        self.last_activity = datetime.now()

class AuthManager:
    """权限管理器"""
    
    def __init__(self):
        self.users: Dict[str, User] = {}
        self.sessions: Dict[str, Session] = {}
        self._init_default_users()
    
    def _init_default_users(self):
        """初始化默认用户"""
        # 创建管理员用户
        admin_password = self._hash_password("admin123")
        admin_user = User("admin", admin_password, [Permission.ADMIN])
        self.users["admin"] = admin_user
        
        # 创建普通用户
        user_password = self._hash_password("user123")
        normal_user = User("user", user_password, [Permission.SELECT, Permission.INSERT])
        self.users["user"] = normal_user
    
    def _hash_password(self, password: str) -> str:
        """密码哈希"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def authenticate(self, username: str, password: str) -> Optional[str]:
        """用户认证，返回会话ID"""
        if username not in self.users:
            return None
        
        user = self.users[username]
        if not user.is_active:
            return None
        
        password_hash = self._hash_password(password)
        if user.password_hash != password_hash:
            return None
        
        # 创建会话
        session_id = secrets.token_hex(32)
        session = Session(user, session_id)
        self.sessions[session_id] = session
        
        # 更新最后登录时间
        user.last_login = datetime.now()
        
        return session_id
    
    def validate_session(self, session_id: str) -> Optional[Session]:
        """验证会话"""
        if session_id not in self.sessions:
            return None
        
        session = self.sessions[session_id]
        if not session.is_active or session.is_expired():
            self.logout(session_id)
            return None
        
        session.update_activity()
        return session
    
    def check_permission(self, session_id: str, permission: str) -> bool:
        """检查权限"""
        session = self.validate_session(session_id)
        if not session:
            return False
        
        return session.user.has_permission(permission)
    
    def logout(self, session_id: str) -> bool:
        """用户登出"""
        if session_id in self.sessions:
            self.sessions[session_id].is_active = False
            del self.sessions[session_id]
            return True
        return False
    
    def create_user(self, admin_session_id: str, username: str, password: str, permissions: List[str]) -> bool:
        """创建用户（需要管理员权限）"""
        if not self.check_permission(admin_session_id, Permission.ADMIN):
            return False
        
        if username in self.users:
            return False
        
        password_hash = self._hash_password(password)
        user = User(username, password_hash, permissions)
        self.users[username] = user
        return True
    
    def get_user_info(self, session_id: str) -> Optional[Dict]:
        """获取用户信息"""
        session = self.validate_session(session_id)
        if not session:
            return None
        
        return {
            "username": session.user.username,
            "permissions": session.user.permissions,
            "last_login": session.user.last_login.isoformat() if session.user.last_login else None,
            "session_created": session.created_at.isoformat()
        }